package com.qfedu.controller;

import cn.hutool.core.util.RandomUtil;
import com.qfedu.entity.ResultVo;
import com.qfedu.util.SMSUtil;
import com.taobao.api.ApiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

/**
 * 作者：刘随阳
 * 时间: 2021/9/20 9:41
 * 描述：神光照耀,太白成瑞。六丙来迎,百福悠归
 */
@RestController
@RequestMapping("/sms")
public class SMSController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping("getSMS")
    public ResultVo getSMS(String phone){
        try {
        if ("".equalsIgnoreCase(phone)){
            return ResultVo.fail( "手机号为空");
        }

        //校验手机号是否合法
        boolean matches = Pattern.matches("^1[3-9]\\d{9}$", phone);
        if (!matches) {
            return  ResultVo.fail( "手机号不合法");
        }

        //随机生成验证码
        String code = RandomUtil.randomNumbers(4);
        SMSUtil.sendMsg(phone,code);


        //验证码存储到Redis
        redisTemplate.boundValueOps("sms:"+phone).set(code);
        redisTemplate.expire("sms:"+phone, 5, TimeUnit.MINUTES);

        return ResultVo.success("success");
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }
}
